/** @file    GadgetWeather.cpp
 *  @author  Alessandro Polo
 *  @version $Id: GadgetWeather.cpp 2808 2010-07-28 20:44:00Z alex $
 *  @brief
 * File containing methods for the wosh::application::GadgetWeather class.
 * The header for this class can be found in GadgetWeather.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/
 
 #include "GadgetWeather.h"
 #include "ui_GadgetWeather.h"

 #include <framework/gui/widgets/wCore_PropertiesProvider.h>
 #include <interfaces/services/Weather.h>
 #include <framework/gui/GuiUtilities.h>


namespace wosh {
  namespace gui {

 WOSH_REGISTER(wosh::gui::GadgetWeather, "wosh::gui::KioskGadgetGeneric", 1.0, _static_GadgetWeather )


class WeatherTableModel : public QAbstractTableModel  {

	public:

		WeatherTableModel(const wosh::Table* table, QObject *parent = 0) : QAbstractTableModel(parent)
		 {
			this->dataTable = NULL;
			loadTable( table );
		 }

		virtual ~WeatherTableModel()
		 {
			if ( this->dataTable != NULL )
				delete this->dataTable; this->dataTable = NULL;
		 }

	public:

		wosh::Table* getDataTable()					{ return this->dataTable; }
		const wosh::Table* getDataTable() const 	{ return this->dataTable; }

		void loadTable( const wosh::Table* table )
		 {
			if ( this->dataTable != NULL )
				delete this->dataTable; this->dataTable = NULL;
			if ( table == NULL )
				return;
			this->dataTable = table->clone();
			reset();
		 }

		void acquireTable( wosh::Table* table)
		 {
			if ( this->dataTable != NULL )
				delete this->dataTable; this->dataTable = NULL;
			this->dataTable = table;
			reset();
		 }

		void updateTable( const wosh::Table* table )
		 {
			if ( this->dataTable == NULL ) {
				loadTable(table);
				return;
			 }
			if ( table == NULL ) {
				delete this->dataTable; this->dataTable = NULL;
				reset();
				return;
			 }
			if ( table->getCols() != this->dataTable->getCols() ) {
				// different colums count => refresh ALL
				loadTable(table);
				return;
			 }

			///@todo may be optimized more!!
			loadTable(table);
			return;
		 }

	public:

		virtual int rowCount(const QModelIndex &parent = QModelIndex()) const
		 {
			(void)parent;
			if ( this->dataTable == NULL ) return 0;
			return this->dataTable->getRows();
		 }

		virtual int columnCount(const QModelIndex &parent = QModelIndex()) const
		 {
			(void)parent;
			if ( this->dataTable == NULL ) return 0;
			return this->dataTable->getCols();
		 }


		virtual QVariant data(const QModelIndex &index, int role) const
		 {
			if ( this->dataTable == NULL || !index.isValid() )
				return QVariant();

			if ( role == Qt::DisplayRole || role == Qt::EditRole ) {
				const ISerializable* object = this->dataTable->get(index.row(), index.column() );
				if ( object == NULL )
					return QVariant();

				return GuiUtilities::convertSerializable2QVariant(object);
			 }
			return QVariant();
		 }

		virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
		 {
			 if (role != Qt::DisplayRole)
				 return QVariant();
			if ( this->dataTable == NULL )
				return QVariant();
			 if (orientation == Qt::Horizontal ) {
				 if ( this->dataTable->hasHeaderHorizontal() ) {
					ISerializable* object = this->dataTable->getHeaderHorizontal(section);
					if ( object == NULL )
						return QString("Col%1").arg(section);
					return GuiUtilities::convertSerializable2QVariant(object);
				 }
				//return QString("Col%1").arg(section);
			 }
			else if (orientation == Qt::Vertical ) {
				if ( this->dataTable->hasHeaderVertical() ) {
					ISerializable* object = this->dataTable->getHeaderVertical(section);
					if ( object == NULL )
						return QString("Row%1").arg(section);
					return GuiUtilities::convertSerializable2QVariant(object);
				 }
				//return QString("Row%1").arg(section);
			 }
			return QVariant();
		 }

	protected:
		wosh::Table* dataTable;

}; // class def


//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS

GadgetWeather::GadgetWeather() : KioskGadgetGeneric()
 {
	this->m_ui = new Ui::GadgetWeather();
	this->m_ui->setupUi(this);

	KioskGadgetGeneric::setTitle(tr("Weather"));
	this->getWidgetURI().setName( Utilities::format("GadgetWeather#%10lu", Utilities::randomLong()) );
	this->getTargetURI().fromString( "*:Bundles/Weather" );

	this->wTableModel = new WeatherTableModel(NULL, this);
	this->m_ui->tableView->setModel(this->wTableModel);

	this->propMapper = new PropertiesMapper(this);
	this->propMapper->getMap().insert(_Weather_KEY_CurrentCondition, this->m_ui->lblSummary);
	this->propMapper->getMap().insert(_Weather_KEY_CurrentWeatherTs, this->m_ui->lblTime);


//	QObject::connect(this->m_ui->pushButton, SIGNAL(clicked()), this, SLOT(refreshAll()));

 }

GadgetWeather::~GadgetWeather()
 {
	delete this->propMapper;
	delete this->m_ui;
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void GadgetWeather::setTargetURI( const URI& uri ) {
	IWidget::setTargetURI(uri);
	if ( uri.isEmpty() || !uri.isValid() )
		IWidget::setTargetURI( URI("*:Bundles/Weather") );
 }

void GadgetWeather::refreshAll() {
	List* dlProps = this->propMapper->createKeysList();
	Request* request_method = new Request( _METHOD_GetProperties, dlProps );
	postMessageForTarget( new Message(request_method) );

	Request* request_forecast = new Request( _Weather_METHOD_get_forecast_tbl );
	postMessageForTarget( new Message(request_forecast) );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void GadgetWeather::busMessage( const Message& message, const Bus* )
 {
	if ( message.isEmpty() ) return;
	if ( !message.getContent()->isResponse() ) return;
	if ( !isMessageForMeOrFromTarget(message) )
		return;
	const wosh::Response* response = message.getContent()->asResponse();

	if ( response->getMethod() == _Weather_METHOD_get_forecast_tbl ) {
		if ( !response->hasData() || !response->getData()->isKindOf<Table>() )
			return;
		const Table* tbl = response->getData()->as<Table>();
		this->wTableModel->loadTable(tbl);
	 }
	else {
		this->propMapper->evalResponse(response);
	 }
 }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

  }; // namespace gui
}; // namespace wosh
